package im

import (
	"context"
	"encoding/json"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"go-websocket/api/im/v1"
	"go-websocket/internal/service"
	"go-websocket/utility"
	"strings"
)


type messageCtl struct {}

var Message = new(messageCtl)

/*
by:axin
发送消息
*/
func (c *messageCtl)TextMsg (r *ghttp.Request) {

	var req *v1.TextMsgReq

	//获取参数
	if err := r.Parse(&req); err != nil {
		//返回错误信息
		r.Response.WriteExit(utility.JsonResult{
			Err: 1,
			Msg: err.Error(),
		})
	}

	//校验参数
	if strings.TrimSpace(req.ListId) == "" || strings.TrimSpace(req.ContentType) == "" || req.Content == nil {
		r.Response.WriteExit(utility.JsonResult{
			Err: 1,
			Msg: "参数错误",
		})
	}

	//转为json处理换行符
	marshal, err := json.Marshal(req.Content)
	if err != nil {
		g.Log().Error(context.TODO(), err)
		r.Response.WriteExit(utility.JsonResult{
			Err: 1,
			Msg: err.Error(),
		})
	}

	tmp := string(marshal)
	tmp = strings.Replace(tmp, "\n", "<br>", -1)

	//转map存mongo
	err = json.Unmarshal([]byte(tmp), &req.Content)

	if err != nil {
		g.Log().Error(context.TODO(), err)
		r.Response.WriteExit(utility.JsonResult{
			Err: 1,
			Msg: err.Error(),
		})
	}

	//发送消息业务逻辑
	err, errCode := service.SendMsg(req, r.Session)
	if err != nil {
		g.Log().Error(context.TODO(), err)
		r.Response.WriteExit(utility.JsonResult{
			Err: errCode,
			Msg: err.Error(),
		})
	} else {
		r.Response.WriteExit(utility.JsonResult{
			Err: errCode,
			Msg: "success",
		})
	}

}